<!DOCTYPE html>
<html>
<head>
	<title>文档管理</title>
	<#include "../../include/head-file.ftl">
	<script src="${base}/static/plugins/clipboard/clipboard.js"></script>
</head>
<body>
<div id="index" class="ms-index" v-cloak>
	<el-header class="ms-header" height="50px">
		<el-col :span="12" style="display: flex">
			<@shiro.hasPermission name="cms:document:create">
				<el-button type="primary" icon="el-icon-plus" size="mini" @click="save()" style="margin-right: 10px;" :disabled="!createFilePermission">新建文件夹</el-button>
			</@shiro.hasPermission>
			<@shiro.hasPermission name="cms:document:upload">
				<el-upload
						ref="uploadFile"
						:action="ms.manager+'/cms/document/upload.do'"
						:style="{width:''}"
						:disabled="false"
						multiple
						:data="{parentDirId:form.parentDirId}"
						:on-success="onUploadSuccess"
						:on-error="onUploadError"
						:before-upload="beforeUpload"
						accept="*"
						:file-list="fileList"
						:show-file-list="false">
					<el-button type="default" icon="el-icon-upload2" size="mini" :loading="uploadLoading" :disabled="!createFilePermission">上传文件</el-button>
				</el-upload>
			</@shiro.hasPermission>
			<@shiro.hasPermission name="cms:document:delete"><!--(selectionList.length==0 && deleteFilePermission) || deleteFilePermission==false -->
				<el-button type="danger" icon="el-icon-delete" size="mini" @click="del(selectionList)"  :disabled="selectionList.length==0" style="margin-right: 10px;margin-left: 10px;">删除</el-button>
			</@shiro.hasPermission>
			<el-button @click="back" icon="iconfont icon-fanhui" size="mini" v-if="form.parentDirId!='ROOT'" style="position: absolute;right: 24px;">返回</el-button>
		</el-col>
	</el-header>
	<div class="ms-search">
		<el-row>
			<el-form :model="form"  ref="searchForm"  label-width="120px" size="mini">
				<el-row>
					<el-col :span="8">
						<el-form-item  label="文件名称" prop="fileName">
							<el-input v-model="form.fileName"
									  :disabled="false"
									  :style="{width:  '100%'}"
									  :clearable="true"
									  placeholder="请输入文件名称">
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item  label="创建人" prop="createdUserName">
							<el-input v-model="form.createdUserName"
									  :disabled="false"
									  :style="{width:  '100%'}"
									  :clearable="true"
									  placeholder="请输入创建人">
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8" style="text-align: right;padding-right: 10px;">
						<el-button type="primary" icon="el-icon-search" size="mini" @click="form.sqlWhere=null;currentPage=1;list()">查询</el-button>
						<el-button @click="rest"  icon="el-icon-refresh" size="mini">重置</el-button>
					</el-col>
				</el-row>
			</el-form>
		</el-row>
	</div>
	<el-main class="ms-container">
		<el-table ref="multipleTable"
				  height="calc(100vh - 20px)"
				  border :data="dataList"
				  row-key="id"
				  v-loading="loading"
				  tooltip-effect="dark"
				  @selection-change="handleSelectionChange">
			<template slot="empty">{{emptyText}}</template>
			<el-table-column type="selection" :selectable="isChecked" width="40"></el-table-column>
			<el-table-column label="名称" align="left" prop="fileOriginName">
				<template slot-scope="scope,text">
						<span @click="open([scope.row])"  style="cursor: pointer;"   v-if="scope.row.fileExt==null">
							<i class="el-icon-folder"  style="color:orange"></i>
							{{ scope.row.fileOriginName }}
						</span>
					<span v-else>
						<i class="el-icon-picture"  style="color:orange" v-if="scope.row.fileExt=='png'||scope.row.fileExt=='jpg'"></i>
						<i class="el-icon-document"  style="color:cornflowerblue" v-else></i>
						{{ scope.row.fileOriginName }}
						</span>

				</template>
			</el-table-column>
			<el-table-column label="编号" width="200" prop="fileCode" show-overflow-tooltip>
			</el-table-column>
			<el-table-column label="创建人" align="center" prop="createdUserName"  width="150">
			</el-table-column>
			<el-table-column label="操作时间" align="center" prop="createdDate"  width="180">
			</el-table-column>
			<el-table-column label="操作" width="250" align="center">
				<template slot-scope="scope">
					<@shiro.hasPermission name="cms:document:view">
						<el-link type="primary" :underline="false" @click="open([scope.row])" v-if="scope.row.fileExt==null">打开</el-link>
						<el-link type="primary" :underline="false" @click="preview([scope.row])" :disabled="scope.row.fileExt!='png' && scope.row.fileExt!='jpg' && scope.row.fileExt!='doc' && scope.row.fileExt!='docx' && scope.row.fileExt!='xls' && scope.row.fileExt!='xlsx' && scope.row.fileExt!='pdf'&& scope.row.fileExt!='txt'" v-else>预览</el-link>
					</@shiro.hasPermission>
					<@shiro.hasPermission name="cms:document:share">
						<el-link type="primary" :underline="false" @click="share([scope.row])">分享</el-link>
					</@shiro.hasPermission>
					<@shiro.hasPermission name="cms:document:download">
						<el-link type="primary" :underline="false" @click="download([scope.row])">下载</el-link>
					</@shiro.hasPermission>
					<@shiro.hasPermission name="cms:document:collect">
						<el-link type="primary" :underline="false" @click="collect([scope.row])" :disabled="scope.row.fileExt==null">收藏</el-link>
					</@shiro.hasPermission>
					<el-link type="primary" :underline="false">
						<el-dropdown @command="command => more(command,[scope.row])" trigger="click">
							  <span class="el-dropdown-link" :disabled="scope.row.morePermissionData.length==0"><!-- :disabled="scope.row.morePermissionData.length==0"-->
								更多操作
							  </span>
							<el-dropdown-menu slot="dropdown">
								<template  v-for="item in scope.row.permissionResponses">
									<el-dropdown-item :command="item.name" v-if="item.enabled && item.name!='创建文件/文件夹'">{{item.name}}</el-dropdown-item>
								</template>
							</el-dropdown-menu>
						</el-dropdown>
					</el-link>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
				background
				:page-sizes="[10,20,30,40,50,100]"
				layout="total, sizes, prev, pager, next, jumper"
				:current-page="currentPage"
				:page-size="pageSize"
				:total="total"
				class="ms-pagination"
				@current-change='currentChange'
				@size-change="sizeChange">
		</el-pagination>
	</el-main>
</div>
</body>
<#include "/cms/document/formUpdate.ftl">
<#include "/cms/document/formShare.ftl">
<#include "/cms/document/formCollect.ftl">
<#include "/cms/document/formMvcp.ftl">
<#include "/cms/document/formLog.ftl">
<#include "/cms/document/formGrant.ftl">
</html>
<script>
    "use strict";
    var indexVue = new Vue({
        el: '#index',
        data: function(){
            return {
				//分类列表
				dataList: [],
				//列表选中
				selectionList: [],
				//列表选中
				total: 0,
				//总记录数量
				pageSize: 10,
				//页面数量
				currentPage: 1,
				//加载状态
				loading: true,
				//提示文字
				emptyText: '',
				manager: ms.manager,
				loadState: false,
				//搜索表单
				form: {
					sqlWhere: null,
					// 文件名称
					fileName: '',
					// 创建人
					createUser: '',
					parentDirId:'ROOT',//父文件夹
				},
				fileList: [],
				uploadLoading:false,
				parentDirOpenIds:['ROOT'],
				parentCurrentPage:[],
				createFilePermission:true,
				createFilePermissions:[true],

			}
        },
        watch: {

        },
        methods: {
            //查询列表
            list: function () {
                var that = this;
                this.loadState = false;
                this.loading = true;
                var page = {
                    pageNo: that.currentPage,
                    pageSize: that.pageSize
                };
                // var form = JSON.parse(JSON.stringify(that.form));
                // for (var key in form) {
                //     if (!form[key]) {
                //         delete form[key];
                //     }
                // }
                var form = that.form
                history.replaceState({
                    form: form,
                    page: page
                }, "");
                ms.http.post(ms.manager + "/cms/document/list.do", form.sqlWhere ? Object.assign({}, {
                    sqlWhere: form.sqlWhere
                }, page): Object.assign({}, form, page),{
                    headers: {
                        'Content-Type': 'application/json'
                    }
                }).then(function (res) {
                    if (that.loadState) {
                        that.loading = false;
                    } else {
                        that.loadState = true;
                    }

                    if (!res.result || res.data.total <= 0) {
                        that.emptyText = '暂无数据';
                        that.dataList = [];
                        that.total = 0;
                    } else {
                        that.emptyText = '';
                        that.total = res.data.total;
                        that.dataList = res.data.records;
                        that.dataList.forEach(function (item) {
                            item.morePermissionData = item.permissionResponses.filter(function (item1) {
                                return item1.enabled && item1.name!=="创建文件/文件夹";
                            });
                            item.permissionResponses.forEach(function (item2) {
                                if(item2.name==="删除"){
                                    item.delPermission = item2.enabled
                                }
                            });
                        });

                    }
                });
                setTimeout(function () {
                    if (that.loadState) {
                        that.loading = false;
                    } else {
                        that.loadState = true;
                    }
                }, 500);
            },
            //分类列表选中
            handleSelectionChange: function (val) {
                this.selectionList = val;
            },
            //删除
            del: function (row) {
                var that = this;
                that.$confirm('此操作将永久删除文件或文件夹, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function () {
                    var fileIds  = [];
                    row.forEach(function (item) {
                        fileIds.push(item.id)
                    });
                    ms.http.post(ms.manager + "/cms/document/delete.do", fileIds, {
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    }).then(function (res) {
                        if (res.result) {
                            that.$notify({
                                title: '成功 ',
                                type: 'success',
                                message: '删除成功!'
                            }); //删除成功，刷新列表

                            that.list();
                        } else {
                            that.$notify({
                                title: '失败',
                                message: res.msg,
                                type: 'warning'
                            });
                        }
                    });
                })
            },

            //表格数据转换
            dataFormat: function (row, column, cellValue, index,dataOptions) {
                var value = "";
                if (cellValue) {
                    var data = dataOptions.find(function (item) {
                        return item.dictValue == cellValue;
                    });
                    if (data && data.dictLabel) {
                        value = data.dictLabel;
                    }
                }
                return value;
            },
            //新增文件夹
            save: function () {
                var that = this;
                var data = {
                    parentDirId:this.form.parentDirId
                }
                ms.http.post(ms.manager + "/cms/document/mkdir.do", data,{
                    headers: {
                        'Content-Type': 'application/json'
                    }
                }).then(function (res) {
                    if(res.code===200){
                        that.$notify({
                            type: 'success',
                            message: "新建文件夹成功"
                        });
                        //新建成功，刷新列表
                        that.list();
                    }else{
                        that.$notify({
                            type: 'error',
                            message: res.msg
                        });
                    }


                }).catch(function (err) {
                    that.$notify({
                        type: 'error',
                        message: "新建文件夹失败"
                    });
                });
            },
            //打开文件夹
            open:function(row){
                var that = this;
                that.parentDirOpenIds.push(row[0].id);
				// this.parentCurrentPage.push(this.currentPage)
                that.form.parentDirId = row[0].id
                that.currentPage = 1;
                row[0].permissionResponses.forEach(function (item) {
                    if(item.name=="创建文件/文件夹" && !item.enabled){
                        that.createFilePermission = false;
                    }
                });
                that.createFilePermissions.push(that.createFilePermission);
            	that.list()
            },
            back:function () {
                if(this.parentDirOpenIds.length>1){
                    this.parentDirOpenIds.pop();
                }
                if(this.createFilePermissions.length>1){
                    this.createFilePermissions.pop();
				}

                this.form.parentDirId = this.parentDirOpenIds[this.parentDirOpenIds.length - 1];
                this.createFilePermission = this.createFilePermissions[this.createFilePermissions.length - 1];
                // var currentPage = this.parentCurrentPage[this.parentCurrentPage.length - 1];
                // if(this.parentCurrentPage.parentCurrentPage>0){
                //     this.parentCurrentPage.pop();
                // }
                this.currentPage = 1;
                this.list();
            },
            //预览
            preview:function(row){
                var oRow = row && row.length>0 ?row[0]: {};
                var filePath = Object.keys(oRow).length>0 && oRow.fileUrl? oRow.fileUrl: null;
                window.parent.indexVue.onlinePreview(filePath);
				ms.http.get(ms.manager + "/log/record/view?fileId="+oRow.id).then(function(res){

				});
                // this.download(row);
                // var url = row[0].fileUrl;
                // console.log("url",url);
                // window.open(ms.base+"/documents"+url,"_blank");
                // var that = this;
                // ms.http.post(ms.manager + "/cms/document/preview.do", {id:row[0].id},{
                //     headers: {
                //         'Content-Type': 'application/json'
                //     }
                // }).then(function (res) {
                //     if(res.code===200){
                //      	console.log("res",res)
                //     }else{
                //         that.$notify({
                //             type: 'error',
                //             message: res.msg
                //         });
                //     }
				//
				//
                // }).catch(function (err) {
                //     that.$notify({
                //         type: 'error',
                //         message: "预览失败"
                //     });
                // });
            },
            //分享
            share:function(row){
                formShare.showShareDialog(row)
            },
            //下载
            download:function(row){
                var that = this
                ms.http.post(ms.manager + "/cms/document/download.do", {id:row[0].id},{
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    responseType:'blob'

                }).then(function (res) {
					if(row[0].fileExt==null){
                        that.downLoadMix(res,row[0].fileOriginName+".zip")
					}else{
                        that.downLoadMix(res,row[0].fileOriginName)
					}


                }).catch(function (err) {
                    that.$notify({
                        type: 'error',
                        message: "下载失败"
                    });
                });
            },
            downLoadMix:function(res, fileName){//new Blob([res],{ type: "application/zip" }
                var blob = new Blob([res]); //res为从后台返回的数据
                if ("msSaveOrOpenBlob" in navigator) {
                    window.navigator.msSaveOrOpenBlob(blob, fileName);
                } else {
                    var link = document.createElement('a')
                    var body = document.querySelector('body')
                    link.href = window.URL.createObjectURL(blob)
                    link.download = fileName
                    link.style.display = 'none'
                    body.appendChild(link)
                    link.click()
                    body.removeChild(link)
                    window.URL.revokeObjectURL(link.href)
                }
			},
            //收藏
            collect:function(row){
                formCollect.showCollectDialog(row)
            },
            //更多操作
            more:function(command,row) {
                if(command === '移动/复制'){//1 移动/复制
                    this.moveCopy(row);
                }else if(command === '查看日志'){//2 查看日志
                    this.log(row);
                }else if(command === '修改名称/编号'){//3 修改名称/编号
                    this.updateN(row);
                }else if(command === '授权管理'){//4 授权管理
                    this.authorize(row);
                }else if(command === '删除'){//5 删除
                    this.del(row)
                }
            },
            //移动复制
            moveCopy:function(row){
                formMvcp.showMvcpDialog(row);
            },
            //查看日志
            log:function(row){
                formLog.showLogDialog(row)
            },
            //修改名称/编号
            updateN:function(row){
                // this.showUpdateDialog(row)
                formUpdate.showUpdateDialog(row);
            },
            //授权管理
            authorize:function(row){
                formGrant.showGrantDialog(row)
            },
            //pageSize改变时会触发
            sizeChange: function (pagesize) {
                this.loading = true;
                this.pageSize = pagesize;
                this.list();
            },
            //currentPage改变时会触发
            currentChange: function (currentPage) {
                this.loading = true;
                this.currentPage = currentPage;
                this.list();
            },
            //重置表单
            rest: function () {
                this.currentPage = 1;
                this.$refs.searchForm.resetFields();
                this.list();
            },
            //上传文件成功回调
            onUploadSuccess: function (response, file, fileList) {
                this.uploadLoading = false
                if(response.code==200){
                    this.$notify({
                        type: 'success',
                        message: "上传成功"
                    });
                    //导入成功，刷新列表
                    this.list();
                }else{
                    this.$notify({
                        type: 'error',
                        message: "上传失败"
                    });
                }
                this.$refs.uploadFile.clearFiles();

            },
            //批量导入失败回调
            onUploadError: function (err, file, fileList) {
                this.$notify({
                    type: 'error',
                    message: "上传失败"
                });
                this.$refs.uploadFile.clearFiles();
            },
            beforeUpload:function(file){
                this.uploadLoading = true;
                return true;
            },
            //不能删除不是自己创建的文件夹/文件
            isChecked: function (row, index) {
				return row.delPermission;
            },
        },
        created: function () {
            if (history.hasOwnProperty("state")) {
                this.form = history.state.form;
                this.currentPage = history.state.page.pageNo;
                this.pageSize = history.state.page.pageSize;
            }
            this.list();
        }
    });
</script>
<style>
	#main .ms-search {
		padding: 20px 0 0;
	}
	#main .ms-container {
		height: calc(100vh - 141px);
	}
	body{
		overflow: hidden;
	}
	/*饿了么滚动样式*/
	.el-scrollbar__wrap{
		overflow-x: scroll !important;
	}
	.el-dropdown-link {
		cursor: pointer;
		color: #409EFF;
	}
	.el-icon-arrow-down {
		font-size: 14px;
	}
</style>